package cn.easyutil.project.web.session;

import cn.easyutil.util.javaUtil.StringUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

public class ServletSessionCache implements SessionCacheFactory {

    private static final String defaultTokenKey = "defaultTokenKey";

    public ServletSessionCache(){
    }

    private String getDefaultKey(String token){
        if(StringUtil.isEmpty(token)){
            token = "";
        }
        return defaultTokenKey+token;
    }

    @Override
    public String getAesKey(String token) {
        return getUserInfo(token, aesKeyName);
    }

    @Override
    public String getUserId(String token) {
        return getUserInfo(token,userIdName);
    }

    @Override
    public void setToken(String token, Long userId) {
        setUserInfo(token,userIdName,userId==null?"":userId.toString());
    }

    @Override
    public void setAesKey(String token, String aesKey) {
        setUserInfo(token,aesKeyName, aesKey);
    }

    @Override
    public void setUserInfo(String token, String key, String val) {
        token = getDefaultKey(token);
        Object sessionValue = getHttpSession().getAttribute(token);
        Map<String, String> userMap;
        if(null == sessionValue){
            userMap = new HashMap<>();
        }else{
            userMap = (Map<String, String>) sessionValue;
        }
        userMap.put(key,val);
        getHttpSession().setAttribute(token, userMap);

    }

    @Override
    public String getUserInfo(String token, String key) {
        token = getDefaultKey(token);
        Object sessionValue = getHttpSession().getAttribute(token);
        if(null == sessionValue) return null;
        Map<String, String> userMap = (Map<String, String>) sessionValue;
        return userMap.get(key);
    }

    @Override
    public void setSmsCode(String phoneNo, String code, long...expire) {
        getHttpSession().setAttribute(cacheSmsPhone+phoneNo,code);
    }

    @Override
    public String getSmsCode(String phoneNo) {
        Object sessionValue = getHttpSession().getAttribute(cacheSmsPhone+phoneNo);
        if(null == sessionValue) return null;
        return (String) sessionValue;
    }

    @Override
    public void removeSmsCode(String phoneNo) {
        getHttpSession().removeAttribute(getKey(phoneNo));
    }

    @Override
    public void removeToken(String token) {
        getHttpSession().removeAttribute(token);
    }

    private HttpSession getHttpSession(){
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest().getSession();
    }


}
